package com.zwj.batch.config.test;

import com.zwj.batch.config.springBatch.incrementer.DailyTimestampParamIncrementer;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;

/**
 * job、step上下文作用域代码验证
 * @author 张文接
 * @version 1.0
 * @createTime 2023-05-28 14:46:30
 */
//@Configuration
public class BatchConfig07 {
    //job构造工厂
    @Resource
    private JobBuilderFactory jobBuilderFactory;
    //step构造工厂
    @Resource
    private StepBuilderFactory stepBuilderFactory;


    @Bean
    public Tasklet tasklet1() {
        return (stepContribution, chunkContext) -> {
            System.err.println("===============step1 开始执行=============");
            //作业
            ExecutionContext jobEC = chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext();
            jobEC.put("key-step1-job", "value-step1-job");
            //步骤
            ExecutionContext stepEC = chunkContext.getStepContext().getStepExecution().getExecutionContext();
            stepEC.put("key-step1-step", "value-step1-step");
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Tasklet tasklet2() {
        return (stepContribution, chunkContext) -> {
            System.err.println("===============step2 开始执行=============");
            //作业
            ExecutionContext jobEC = chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext();
            System.err.println(jobEC.get("key-step1-job"));
            //步骤
            ExecutionContext stepEC = chunkContext.getStepContext().getStepExecution().getExecutionContext();
            System.err.println(stepEC.get("key-step1-step"));
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Job job() {
        return jobBuilderFactory
                .get("execution-context-job")
                .incrementer(dailyTimestampParamIncrementer())
                .start(step1())
                .next(step2())
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory
                .get("step1")
                .tasklet(tasklet1())
                .build();
    }

    @Bean
    public Step step2() {
        return stepBuilderFactory
                .get("step2")
                .tasklet(tasklet2())
                .build();
    }


    @Bean
    public DailyTimestampParamIncrementer dailyTimestampParamIncrementer() {
        return new DailyTimestampParamIncrementer();
    }
}
